package com.wlps.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wlps.contant.Contant;
import com.wlps.entity.CommodityWarehouse;
import com.wlps.entity.FirstClassification;
import com.wlps.entity.SecondClassification;
import com.wlps.mapper.FirstClassificationMapper;
import com.wlps.result.ResultPageVo;
import com.wlps.result.ResultUtils;
import com.wlps.result.ResultVo;
import com.wlps.service.IFirstClassificationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wlps.vo.sendcenter.commodity.FirstClassificationVo;
import com.wlps.vo.sendcenter.warehouse.WarehouseSettingVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 一级分类表(first_classification)(删除一级分类时下面不能存在二级分类) 服务实现类
 * </p>
 *
 * @author ZWYZY
 * @since 2020-07-31
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class FirstClassificationServiceImpl extends ServiceImpl<FirstClassificationMapper, FirstClassification> implements IFirstClassificationService, InitializingBean {

    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        initFirstClassificationVo();
    }

    /**
     * 初始化缓存
     */
    void initFirstClassificationVo() {
        List<FirstClassificationVo> firstClassificationVoList;
        if (!redisTemplate.hasKey(Contant.FIRSTCLASSIFICATIONVOS_KEY)) {
            firstClassificationVoList = baseMapper.selectFirstClassificationCount();
            firstClassificationVoList.stream().forEach(x -> {
                baseMapper.selectSecondClassificationCount().stream().forEach(y -> {
                    if (x.getFirstName().equals(y.getFirstName())) {
                        x.setSecondClassificationNum(y.getSecondClassificationNum());
                    }
                });
                x.setSecondClassificationsList(baseMapper.selectSecondClassificationList().stream().filter(z -> z != null && z.getFirstId().equals(x.getId())).collect(Collectors.toList())
                );
            });

            redisTemplate.opsForValue().set(Contant.FIRSTCLASSIFICATIONVOS_KEY, firstClassificationVoList, 5, TimeUnit.MINUTES);
            log.info("初始化所有一级分类-------存入缓存数据");
        }


    }


    @Override
    public ResultVo addFirstClassification(String firstName) {

        List<FirstClassification> firstClassifications = baseMapper.selectList(new QueryWrapper<FirstClassification>().lambda().eq(FirstClassification::getFirstName, firstName));
        if (firstClassifications.size() != 0) {
            return ResultUtils.error("系统已有同名名称的分类，请换个名称试试，亲", 60000);
        }
        FirstClassification firstClassification = new FirstClassification();
        firstClassification.setFirstName(firstName);
        baseMapper.insert(firstClassification);
        firstClassificationVoUpdateCache();
        return ResultUtils.success("操作成功");
    }


    @Override
    public ResultPageVo<List<FirstClassificationVo>> getFirstClassification(int pageNum, int pageSize, String
            firstName) {
        initFirstClassificationVo();
        //总条数
        int count;
        //偏移量
        int fromNum;
        //终止量
        int toNum;
        List<FirstClassificationVo> firstClassificationVoList = (List<FirstClassificationVo>) redisTemplate.opsForValue().get(Contant.FIRSTCLASSIFICATIONVOS_KEY);
        if (firstName == null) {
            //不是条件查询，redis
            count = firstClassificationVoList.size();

        } else {
            Stream<FirstClassificationVo> stream = firstClassificationVoList.stream();
            stream = stream.filter(x -> x != null && firstName.equals(x.getFirstName()));
            firstClassificationVoList = stream.collect(Collectors.toList());
            count = firstClassificationVoList.size();
        }
        //当前页从第几条开始查
        fromNum = pageSize * (pageNum - 1);
        if (fromNum >= count) {
//            sysUserList=null;
        } else {
            //当前页最后第几条
            toNum = fromNum + pageSize >= count ? count : fromNum + pageSize;
            firstClassificationVoList = firstClassificationVoList.subList(fromNum, toNum);
        }


        //分页返回值封装
        ResultPageVo resultPageVo = new ResultPageVo("响应成功", 200, (long) pageSize, (long) pageNum, (long) count, firstClassificationVoList);
        return resultPageVo;
    }

    /**
     * 更新缓存
     */
    @Async
    public void firstClassificationVoUpdateCache() {

        List<FirstClassificationVo> firstClassificationVoList = baseMapper.selectFirstClassificationCount();
        firstClassificationVoList.stream().forEach(x -> {
            baseMapper.selectSecondClassificationCount().stream().forEach(y -> {
                if (x.getFirstName().equals(y.getFirstName())) {
                    x.setSecondClassificationNum(y.getSecondClassificationNum());
                }
            });
            x.setSecondClassificationsList(baseMapper.selectSecondClassificationList().stream().filter(z -> z != null && z.getFirstId().equals(x.getId())).collect(Collectors.toList())
            );
        });

        redisTemplate.opsForValue().set(Contant.FIRSTCLASSIFICATIONVOS_KEY, firstClassificationVoList, 5, TimeUnit.MINUTES);
        log.info("更新所有一级分类-------存入缓存数据");

    }

}
